import json
import re
from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from libs.qiniuyun.qiniu_storage import storage
from users.models import User
import logging

from utils.model import BaseModel
from utils.view import LoginRequiredMixin

logger = logging.getLogger('django')


class RegisterView(View):

    def post(self, request):
        """注册功能"""
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        phone_code = json_dict.get('phonecode')
        password = json_dict.get('password')
        if not all([mobile, password, phone_code]):
            return JsonResponse({'errno': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'errno': 400, 'errmsg': 'password格式有误'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': 400, 'errmsg': 'mobile格式有误'})
        # 进行redis操作查询手机号验证码
        try:
            redis_conn = get_redis_connection('verify_code')
            sms_code_server = redis_conn.get('sms_code_%s' % mobile)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 400, 'errmsg': 'redis操作失败'})
        if phone_code != sms_code_server.decode():
            return JsonResponse({'errno': 400, 'errmsg': '验证码有误'})
        if not sms_code_server:
            return JsonResponse({'errno': 400, 'errmsg': '短信验证码不存在或已过期,请检查手机号后重试'})
        # 数据库查询是否有相同手机号
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return JsonResponse({'errno': 400, 'errmsg': '查询数据库出错'})
        if count == 1:
            return JsonResponse({'errno': 400, 'errmsg': '手机号重复'})
        # 保存用户注册信息
        try:
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 400, 'errmsg': 'mysql写入错误'})
        login(request, user)
        return JsonResponse({'errno': 0, 'errmsg': '注册成功'})


class LoginView(View):

    def post(self, request):
        """登录功能"""
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')
        if not all([mobile, password]):
            return JsonResponse({'errno': 400, 'errmsg': '缺少必传参数'})
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'errno': 400, 'errmsg': 'password格式有误'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': 400, 'errmsg': 'mobile格式有误'})
        print(mobile, password)
        try:
            user = authenticate(username=mobile, password=password)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 400, 'errmsg': '手机号或密码错误'})
        if not user:
                return JsonResponse({'errno': 400, 'errmsg': '用户名或密码错误'})
        login(request, user)
        return JsonResponse({'errno': 0, 'errmsg': 'ok'})


    def get(self, request):
        """确认登录状态"""
        if not request.user.is_authenticated:
            return JsonResponse({'errno': 4101, 'errmsg': '未登录'})
        else:
            data = {
                'user_id': request.user.id,
                'name': request.user.username
            }

        return JsonResponse({'errno': 0, 'errmsg': '已登录', 'data': data})

    def delete(self, request):
        """退出登录"""
        logout(request)
        response = JsonResponse({'errno': 0, 'errmsg': '已登出'})
        response.delete_cookie('username')
        return response


# 上传头像
class AvatarView(View):

    def post(self, request):
        image = request.FILES.get('avatar')
        try:
            url = storage(image.read())
        except Exception as e:
            return JsonResponse({'errno': 400, 'errmsg': '上传失败'})
        try:
            request.user.avatar = url
            request.user.save()
        except Exception as e:
            return JsonResponse({'errno': 400, 'errmsg': 'mysql保存图片地址失败'})
        data = {'avatar_url': settings.QINIU_URL + url}
        return JsonResponse({'errno': 0, 'errmsg': '头像上传成功', 'data': data})


# 用户中心
class UserInfoView(LoginRequiredMixin, View):
    def get(self, request):
        user = request.user
        avatar = str(user.avatar)
        data = {
            "avatar_url": settings.QINIU_URL + avatar,
            "create_time": user.date_joined,
            "mobile": user.mobile,
            "name": user.username,
            "user_id": user.id,
        }
        return JsonResponse({'errmsg': 'OK', 'errno': 0, 'data': data})


# 用户名修改
class UserChangeNameView(LoginRequiredMixin, View):
    def put(self, request):
        json_dict = json.loads(request.body.decode())
        username = json_dict.get('name')
        user = request.user
        try:
            user.username = username
            user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4004, 'errmsg': '数据错误'})
        return JsonResponse({'errno': 0, 'errmsg': '修改成功'})


# 实名认证
class UserAuthView(LoginRequiredMixin, View):
    # 房源显示认证信息
    def get(self, request):
        user = request.user
        data = {
            'real_name': user.real_name,
            'id_card': user.id_card
        }
        return JsonResponse({'errno': 0, 'errmsg': '认证信息保存成功', 'data': data})

    # 保存用户认证信息
    def post(self, request):
        # 1.接收参数
        json_dict = json.loads(request.body.decode())
        real_name = json_dict.get('real_name')
        id_card = json_dict.get('id_card')
        # 2.校验参数
        if not all([real_name, id_card]):
            return JsonResponse({'errno': 4103, 'errmsg': '参数错误'})
        if not re.match(
                r'^([1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)',
                id_card):
            return JsonResponse({'errno': 4103, 'errmsg': '参数错误'})

        # 3.保存数据库
        try:
            request.user.real_name = real_name
            request.user.id_card = id_card
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4004, 'errmsg': '数据错误'})

        # 4.返回响应
        return JsonResponse({'errno': 0, 'errmsg': '认证信息保存成功'})
